package host

import (
	"fmt"
	"kubeInstall/install"
	"kubeInstall/pkg/client/db"
	"kubeInstall/server/models/cluster"
	"kubeInstall/utils/uuid"
)

func GetHost(hostId string) (*cluster.Host, error) {
	var host cluster.Host
	err := db.Db.Where("host_id = ?", hostId).First(&host).Error

	if err != nil {
		if err == db.ErrRecordNotFound {
			return nil, fmt.Errorf("host ID %s not found", hostId)
		}
		return nil, err
	}

	err = db.Db.Model(&host).Related(&host.Credential).Error
	if err != nil && err != db.ErrRecordNotFound {
		return nil, err
	}

	/*	err = Db.Model(&host).Preload("HostTag").Find(&host).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return nil, err
		}*/

	return &host, nil

}

func GetHostRoleByClusterId(clusterId string, role string) ([]cluster.Host, error) {
	var hostList []cluster.Host

	err := db.Db.Preload("Credential").Select("*").Where("cluster_id = ?&& role = ?", clusterId, role).Find(&hostList).Error

	if err != nil {
		return hostList, err
	}

	return hostList, nil
}

func UpdateHostByClusterId(hostId, clusterId string, role string) error {

	err := db.Db.Model(&cluster.Host{}).Where("host_id = ?", hostId).Updates(map[string]interface{}{"cluster_id": clusterId, "role": role, "used": true}).Error
	if err != nil {
		return err
	}

	return nil
}

func ListHosts(limit, Offset int) ([]*cluster.Host, error) {
	var hostList []*cluster.Host
	if limit == 0 {
		limit = 10
	}

	err := db.Db.Preload("Credential").Select("*").Limit(limit).Offset((Offset - 1) * limit).Find(&hostList).Error

	if err != nil {
		return hostList, err
	}

	return hostList, nil
}

func CheckIpIsValid(ip string) bool {

	var count int

	db.Db.Model(cluster.Host{}).Where("ip = ?", ip).Count(&count)
	if count > 0 {
		return false
	}

	return true
}

func CheckHostNameIsValid(hostname string) bool {

	var count int

	db.Db.Model(cluster.Host{}).Where("host_name = ?", hostname).Count(&count)
	if count > 0 {
		return false
	}

	return true
}

func CheckHostIsUsed(hostId string) bool {

	var count int

	db.Db.Model(cluster.Host{}).Where("host_id= ?&& used = true", hostId).Count(&count)
	if count > 0 {
		return true
	}

	return false
}

func CreateHost(h *cluster.Host) (*cluster.Host, error) {

	// 验证主机

	h.ID = uuid.GenUUID()
	if err := db.Db.Create(&h).Error; err != nil {
		return nil, err
	}

	err := db.Db.Model(&h).Related(&h.Credential).Error
	if err != nil && err != db.ErrRecordNotFound {
		return nil, err
	}

	return h, nil
}

func CheckHostIsActive(sshOpt *install.SShOptions) (error, string) {

	h, err := install.NewAsyncHandler(sshOpt)
	if err != nil {
		return err, "Unknown"
	}
	return nil, h.GetHostType()

}

func DeleteHost(hostId string) error {
	var host cluster.Host
	err := db.Db.Where("host_id = ?", hostId).Delete(&host).Error

	return err
}

func UpdateHost(hostId string, h *cluster.Host) error {
	err := db.Db.Preload("Credential").Model(&cluster.Host{}).Where("host_id = ?", hostId).Update(&h).Error
	return err
}
